﻿using AOT.Game.Timer;
using Net.Msg;
using Net.Public.EventSystem;
using Net.Public.Helper;
using Net.Public.Msg;
using Net.Runtime.Base;

namespace Net.Public.Client
{
    public class RpcClient : BaseRpc
    {
        private bool canSendMsg = false;
        private WClient _wClient;
        private HeartMsg _heartMsg;
        private BaseMsg heartMsg;
        public Action<RpcClient> onConnectFunc;
        public Action<RpcClient> updateAction;
        public int ClientID => _wClient.ID;

        public override void OnStart(ScriptTimer _timer, string ip, int port)
        {
            _wClient = new WClient(ip, port);
            RpcEventSystem.Instance.RegisterMsg(EMsgType.LoginMsg, (msg) =>
            {
                LoginMsg loginMsg = msg as LoginMsg;
                canSendMsg = true;
                _wClient.ID = loginMsg.ClientId;
                _heartMsg = new HeartMsg();
                _heartMsg.ClientId = loginMsg.ClientId;
                heartMsg = new BaseMsg(_heartMsg, EMsgType.HeartMsg);
                onConnectFunc?.Invoke(this);
                Debugger.Log($"客户端得到自己的编号{loginMsg.ClientId}");
            });
            base.OnStart(_timer, ip, port);
            _wClient.Start();
        }

        public override void OnUpdate()
        {
            base.OnUpdate();
            if(heartMsg!=null) 
                SendMsgToServer(heartMsg);
            updateAction?.Invoke(this);
        }

        public void SendMsgToServer(BaseMsg msg) => _wClient.SendMsgToServer(msg);
        public void SendLoginMsgToServer(BaseMsg loginMsg) => SendMsgToServer(loginMsg);

        public override void OnClose()
        {
            base.OnClose();
            canSendMsg = false;
            _wClient.Dispose();
        }
    }
}